//
//  MWRegisterPhoneController.m
//  XiRan-iOS
//
//  Created by Richfit on 2020/3/14.
//  Copyright © 2020 Wood. All rights reserved.
//

#import "MWRegisterPhoneController.h"
#import "MWCountryCodeController.h"

#import "MWTabBarController.h"

#import "CQCountDownButton.h"
#import "JKCountDownButton.h"

#import "MWUser.h"

#import "HLPopTableView.h"
#import "UIView+HLExtension.h"

@interface MWRegisterPhoneController ()

@property(nonatomic, strong) UIButton *backBtn;
@property(nonatomic, strong) UILabel *hintLB;
@property(nonatomic, strong) UIButton *phoneBtn;
@property(nonatomic, strong) UITextField *phoneTF;
@property(nonatomic, strong) UIView *phoneLineView;

@property(nonatomic, strong) UITextField *smsCodeTF;
@property(nonatomic, strong) JKCountDownButton *countDownButton;
@property(nonatomic, strong) UIView *smsCodeLineView;

@property(nonatomic, strong) UITextField *password1TF;
@property(nonatomic, strong) UIView *passwordLine1View;

@property(nonatomic, strong) UITextField *password2TF;
@property(nonatomic, strong) UIView *passwordLine2View;

@property(nonatomic, strong) UIButton *registerBtn;

@property(nonatomic, strong) MWUser *user;
@property(nonatomic, strong) NSString *countryCode;

@end

@implementation MWRegisterPhoneController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupPageSubviews];
    [self layoutPageSubviews];
    [self setLocalizable];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void)backAction:(UIButton *)sender {
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)phoneAction:(UIButton *)sender {
    MWCountryCodeController *controller = [[MWCountryCodeController alloc] init];
    MWWeakSelf
    controller.countryCodeBlock = ^(NSString *countryCode) {
        weakSelf.countryCode = countryCode;
        [weakSelf.phoneBtn setTitle:[NSString stringWithFormat:@"+%@", countryCode] forState:UIControlStateNormal];
        [weakSelf.phoneBtn setIconInRightWithSpacing:5];
    };
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)registerAction:(UIButton *)sender {
    [self.view endEditing:YES];
    NSString *phone = _phoneTF.text;
    NSString *code = _smsCodeTF.text;
    NSString *password1 = _password1TF.text;
    NSString *password2 = _password2TF.text;
    
    if (![password1 isEqualToString:password2]) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = [[MWConfigManager manager] objectForKey:@"pwd_error" defaultValue:@"两次输入的密码不一致"];
        [hud hideAnimated:YES afterDelay:2];
        return;
    }
    
    [self registerWithPhone:phone code:code countryCode:_countryCode password:password1];
}

#pragma mark - 验证码请求
- (void)loadSmsCodeWithPhone:(NSString *)phone countryCode:(NSString *)countryCode {
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:phone forKey:@"mobile"];
    [paraDic setObject:countryCode forKey:@"country_code"];
    [paraDic setObject:@"register" forKey:@"event"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kSmsCodeUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        
        hud.mode = MBProgressHUDModeText;
        hud.label.text = msg;
        [hud hideAnimated:YES afterDelay:2];
        
        if (code == 1) {
            weakSelf.countDownButton.enabled = NO;
            [weakSelf.countDownButton startCountDownWithSecond:60];
        }
        
    } failure:^(NSError *error) {
        [hud hideAnimated:YES];
    }];
}

#pragma mark - 注册请求
- (void)registerWithPhone:(NSString *)phone code:(NSString *)code countryCode:(NSString *)countryCode password:(NSString *)password {
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:phone forKey:@"mobile"];
    [paraDic setObject:password forKey:@"password"];
    [paraDic setObject:code forKey:@"code"];
    [paraDic setObject:countryCode forKey:@"country_code"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.label.text = [[MWConfigManager manager] objectForKey:@"loadin" defaultValue:@"加载中..."];
    
    [[MWNetworkManager manager] POST:kRegisterUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        if (code == 1) {
            [hud hideAnimated:YES];
            NSDictionary *dataDic = [dic objectForKey:@"data"];
            MWUser *user = [MWUser mj_objectWithKeyValues:[dataDic objectForKey:@"userinfo"]];
            [MWUserManager manager].user = user;
            [[MWUserManager manager] saveUser];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kLoginResultNotification object:nil];
            self.navigationController.navigationBarHidden = NO;
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        } else {
            hud.mode = MBProgressHUDModeText;
            hud.label.text = msg;
            [hud hideAnimated:YES afterDelay:2];
        }
        
    } failure:^(NSError *error) {
        [hud hideAnimated:YES];
    }];
}

#pragma mark - 国际化
- (void)setLocalizable {
    if ([[MWConfigManager manager].productType isEqualToString:@"0"]) {
        _hintLB.text = [[MWConfigManager manager] objectForKey:@"welcome_into_wood" defaultValue:@"欢迎来到我的木头"];
    } else {
        _hintLB.text = [[MWConfigManager manager] objectForKey:@"welcome_into_xiran" defaultValue:@"欢迎来到木头猎人"];
    }
    _phoneTF.placeholder = [[MWConfigManager manager] objectForKey:@"input_phone" defaultValue:@"请输入手机号"];
    _smsCodeTF.placeholder = [[MWConfigManager manager] objectForKey:@"input_code" defaultValue:@"请输入验证码"];
    [_countDownButton setTitle:[[MWConfigManager manager] objectForKey:@"get_code" defaultValue:@"获取验证码"] forState:UIControlStateNormal];
    _password1TF.placeholder =  [[MWConfigManager manager] objectForKey:@"input_pwd" defaultValue:@"请输入密码"];
    _password2TF.placeholder =  [[MWConfigManager manager] objectForKey:@"input_pwd_again" defaultValue:@"请再次输入密码"];
    [_registerBtn setTitle:[[MWConfigManager manager] objectForKey:@"register" defaultValue:@"注册"] forState:UIControlStateNormal];
}

#pragma mark - UI
- (void)setupPageSubviews {
    _countryCode = @"86";
    _phoneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _phoneBtn.titleLabel.font = MWFont(14);
    [_phoneBtn setTitle:@"+86" forState:UIControlStateNormal];
    [_phoneBtn setTitleColor:MWHexColor(@"#1E1934") forState:UIControlStateNormal];
    [_phoneBtn setImage:[UIImage imageNamed:@"ic_arrow_down"] forState:UIControlStateNormal];
    [_phoneBtn addTarget:self action:@selector(phoneAction:) forControlEvents:UIControlEventTouchUpInside];
    [_phoneBtn setIconInRightWithSpacing:5];
    [self.view addSubview:_phoneBtn];
    
    _phoneTF = [[UITextField alloc] init];
    _phoneTF.font = MWFont(14);
    _phoneTF.textColor = MWHexColor(@"#BAC2CE");
    [self.view addSubview:_phoneTF];
    
    
    _phoneLineView = [[UIView alloc] init];
    _phoneLineView.backgroundColor = MWHexColor(@"#D8D8D8");
    [self.view addSubview:_phoneLineView];
    
    _smsCodeTF = [[UITextField alloc] init];
    _smsCodeTF.keyboardType = UIKeyboardTypeNumberPad;
    _smsCodeTF.font = MWFont(14);
    _smsCodeTF.textColor = MWHexColor(@"#BAC2CE");
    [self.view addSubview:_smsCodeTF];
    
    _smsCodeLineView = [[UIView alloc] init];
    _smsCodeLineView.backgroundColor = MWHexColor(@"#D8D8D8");
    [self.view addSubview:_smsCodeLineView];
    
    _countDownButton = [JKCountDownButton buttonWithType:UIButtonTypeCustom];
    _countDownButton.titleLabel.font = MWFont(12);
    [_countDownButton setTitleColor:MWHexColor(@"#1E1934") forState:UIControlStateNormal];
    [self.view addSubview:_countDownButton];
    
    MWWeakSelf
    [_countDownButton countDownButtonHandler:^(JKCountDownButton*sender, NSInteger tag) {
        NSString *phone = weakSelf.phoneTF.text;
        [self loadSmsCodeWithPhone:phone countryCode:weakSelf.countryCode];
       
        [sender countDownChanging:^NSString *(JKCountDownButton *countDownButton,NSUInteger second) {
            NSString *title = [NSString stringWithFormat:@"%zds",second];
            return title;
        }];
        
        [sender countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
            countDownButton.enabled = YES;
            return [[MWConfigManager manager] objectForKey:@"getcode_retry" defaultValue:@"重新获取验证码"];
        }];
    }];

    _password1TF = [[UITextField alloc] init];
    _password1TF.secureTextEntry = YES;
    _password1TF.font = MWFont(14);
    _password1TF.textColor = MWHexColor(@"#BAC2CE");
    [self.view addSubview:_password1TF];
    
    _passwordLine1View = [[UIView alloc] init];
    _passwordLine1View.backgroundColor = MWHexColor(@"#D8D8D8");
    [self.view addSubview:_passwordLine1View];
    
    _password2TF = [[UITextField alloc] init];
    _password2TF.secureTextEntry = YES;
    _password2TF.font = MWFont(14);
    _password2TF.textColor = MWHexColor(@"#BAC2CE");
    [self.view addSubview:_password2TF];
    
    _passwordLine2View = [[UIView alloc] init];
    _passwordLine2View.backgroundColor = MWHexColor(@"#D8D8D8");
    [self.view addSubview:_passwordLine2View];
    
    _registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _registerBtn.layer.cornerRadius = 5;
    _registerBtn.layer.masksToBounds = YES;
    _registerBtn.titleLabel.font = MWFont(14);
    [_registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_registerBtn setBackgroundImage:[UIImage imageWithColor:MWHexColor(@"#1E1934")] forState:UIControlStateNormal];
    [_registerBtn addTarget:self action:@selector(registerAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_registerBtn];
    
}

- (void)layoutPageSubviews {
    [_phoneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(16);
        make.centerY.equalTo(self.phoneTF);
        make.width.equalTo(@80);
        make.height.equalTo(@20);
    }];
    [_phoneBtn setIconInRightWithSpacing:5];
    
    [_phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(48);
        make.left.equalTo(self.phoneBtn.mas_right).offset(10);
        make.right.equalTo(self.view).offset(-16);
    }];
    
    [_phoneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneTF.mas_bottom).offset(6);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
        make.height.equalTo(@0.5);
    }];
    
    [_smsCodeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneLineView.mas_bottom).offset(23);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
    }];
    
    [_countDownButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-16);
        make.centerY.equalTo(self.smsCodeTF);
    }];
    
    [_smsCodeLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.smsCodeTF.mas_bottom).offset(6);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
        make.height.equalTo(@0.5);
    }];
    
    [_password1TF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.smsCodeLineView.mas_bottom).offset(23);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
    }];
    
    [_passwordLine1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.password1TF.mas_bottom).offset(6);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
        make.height.equalTo(@0.5);
    }];
    
    [_password2TF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordLine1View.mas_bottom).offset(23);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
    }];
    
    [_passwordLine2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.password2TF.mas_bottom).offset(6);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
        make.height.equalTo(@0.5);
    }];
    
    [_registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordLine2View.mas_bottom).offset(82);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
        make.height.equalTo(@44);
    }];
}

@end
